package cn.practice.chat.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @ClassName JwtUtils
 * @Description:
 * @Author A-TAO
 * @Date 2022/10/30
 * @Version V1.0
 **/
@Data
@Component
@ConfigurationProperties(prefix = "jwt")
public class JwtUtils {

    private long expire;
    private String secret;
    private String header;
    /**
     * @description 根据账号生成token
     * @param username
     * @return {@link java.lang.String}
     **/
    public String generateToken(String username){

        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + 1000 * expire);
        return Jwts.builder()
                .setHeaderParam("typ","JWT")
                .setSubject(username)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)//7天逾期
                .signWith(SignatureAlgorithm.HS512,secret)
                .compact();
    }

    /**
     * @description 解析token
     * @param jwtToken
     * @return {@link io.jsonwebtoken.Claims}
     **/
    public Claims getClaimByToken(String jwtToken){
        try{
            return   Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(jwtToken)
                    .getBody();
        }catch (Exception e){
            return null;
        }
    }
    /**
     * @description 验证token是否过期
     * @param claims
     * @return {@link boolean}
     **/
    public boolean isTokenExpired(Claims claims){
        return claims.getExpiration().before(new Date());
    }
}
